var express = require('express');
const fs = require('fs');
const path = require('path');
const { jsonCRUDGenerator } = require('../utils');
const moment = require('moment');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

const todoFile = `${path.join(__dirname, '..', 'db')}\\TODO.json`;
const { C: todoC, R: todoR, U: todoU, D: todoD } = jsonCRUDGenerator(todoFile);
router.post('/todo/create', todoC);
router.get('/todo/get', (req, res, next) => {
  const dbFile = todoFile;
  const type = req.query.type || 0;

  if (!fs.existsSync(dbFile)) {
    fs.writeFileSync(dbFile, '[]');
  }
  fs.readFile(dbFile, 'utf8', (err, data) => {
    if (err) {
      res.send({
        data: [],
        code: 0,
        msg: err,
      });
      return;
    }
    res.send({
      data: JSON.parse(data).filter(i => i.status === Number(type)),
      code: 1,
      msg: '',
    });
  });
});
router.get('/todo/statistics', (req, res, next) => {
  const dbFile = todoFile;
  if (!fs.existsSync(dbFile)) {
    fs.writeFileSync(dbFile, '[]');
  }
  fs.readFile(dbFile, 'utf8', (err, data) => {
    if (err) {
      res.send({
        data: [],
        code: 0,
        msg: err,
      });
      return;
    }
    const allData = JSON.parse(data);
    const [doing, done] = [
      allData.filter(i => i.status === 0),
      allData.filter(i => i.status === 1),
    ];
    const today = new Date().toISOString().split('T')[0];
    // 进行中，结束时间是今天
    const todaysRemain = doing.filter(i =>
      moment(i.endTime.split('T')[0]).isSame(moment(today))
    ).length;
    // 进行中，结束日期是今天之前
    const outdated = doing.filter(i =>
      moment(i.endTime.split('T')[0]).isBefore(moment(today))
    ).length;
    // 进行中，开始时间是今天之前
    const allRemain = doing.filter(i => {
      const startDay = moment(i.startTime.split('T')[0]);
      return startDay.isSameOrBefore(moment(today));
    }).length;
    // 进行中，尚未开始
    const waitToStart = doing.filter(i => {
      const startDay = moment(i.startTime.split('T')[0]);
      return startDay.isAfter(moment(today));
    }).length;
    // 已完成，完成时间是今天
    const todaysFinished = done.filter(i =>
      moment(i.finishTime.split('T')[0]).isSame(moment(today))
    ).length;
    // 所有已完成
    const allFinished = done.length;

    res.send({
      data: {
        todaysRemain,
        outdated,
        todaysFinished,
        allFinished,
        allRemain,
        waitToStart,
      },
      code: 1,
      msg: '',
    });
  });
});
router.post('/todo/update', todoU);
router.post('/todo/remove', todoD);

const checkFile = `${path.join(__dirname, '..', 'db')}\\CHECK.json`;
const { C: checkC, R: checkR, U: checkU, D: checkD } = jsonCRUDGenerator(checkFile);
router.post('/check/create', checkC);
router.get('/check/get', checkR);
router.post('/check/update', checkU);
router.post('/check/remove', checkD);

const planFile = `${path.join(__dirname, '..', 'db')}\\PLAN.json`;
const { C: planC, R: planR, U: planU, D: planD } = jsonCRUDGenerator(planFile);
router.post('/plan/create', planC);
router.get('/plan/get', planR);
router.post('/plan/update', planU);
router.post('/plan/remove', planD);

const memoFile = `${path.join(__dirname, '..', 'db')}\\MEMO.json`;
const { C: memoC, R: memoR, U: memoU, D: memoD } = jsonCRUDGenerator(memoFile);
router.post('/memo/create', memoC);
router.get('/memo/get', memoR);
router.post('/memo/update', memoU);
router.post('/memo/remove', memoD);

const timelineFile = `${path.join(__dirname, '..', 'db')}\\TIMELINE.json`;
const { C: timelineC, R: timelineR, U: timelineU, D: timelineD } = jsonCRUDGenerator(timelineFile);
router.post('/timeline/create', timelineC);
router.get('/timeline/get', timelineR);
router.post('/timeline/update', timelineU);
router.post('/timeline/remove', timelineD);

router.get('/db/export', (req, res, next) => {
  const keys = ['TODO', 'CHECK', 'PLAN', 'MEMO', 'TIMELINE'];
  const exportData = {};

  const msg = [];
  keys.forEach(k => {
    try {
      const dbFile = `${path.join(__dirname, '..', 'db')}\\${k}.json`;
      if (!fs.existsSync(dbFile)) {
        fs.writeFileSync(dbFile, '[]');
      }
      exportData[k] = JSON.parse(fs.readFileSync(dbFile, 'utf8'));
    } catch (e) {
      exportData[k] = [];
      msg.push(String(e));
    }
  });
  res.send({
    data: exportData,
    code: msg.length ? 0 : 1,
    msg: msg.join(';'),
  });
});
router.post('/db/import', (req, res, next) => {
  const importData = req.body;

  const keys = ['TODO', 'CHECK', 'PLAN', 'MEMO', 'TIMELINE'];

  const msg = [];
  keys.forEach(k => {
    try {
      const dbFile = `${path.join(__dirname, '..', 'db')}\\${k}.json`;
      if (!fs.existsSync(dbFile)) {
        fs.writeFileSync(dbFile, '[]');
      }
      fs.writeFileSync(dbFile, JSON.stringify(importData?.[k] || []));
    } catch (e) {
      msg.push(`${k}导入失败`);
    }
  });
  res.send({
    data: [],
    code: msg.length ? 0 : 1,
    msg: msg.join(';'),
  });
});

module.exports = router;
